package com.ntt.DB;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionFactory {
//	声明一个静态连接对象，即ConnectionFactory每次获得的连接对象都是同一个对象
	private static Connection conn=null;
	// 建立属性对象
	private static Properties pro = new Properties();
	// 声明相关参数
    private static String driver;
    private static String url;
    private static String dbname;
    private static String uid;
    private static String pwd;
	
//	声明静态方法，获得数据库连接
	public static Connection getConnection(){
		try {
			pro.load(ConnectionFactory.class.getResourceAsStream("dbinfo.properties"));
			// 建立公有的属性
			driver = pro.getProperty("driver");
			url = pro.getProperty("url");
			dbname = pro.getProperty("dbname");
			uid = pro.getProperty("uid");
			pwd = pro.getProperty("pwd");
			// 建立属性对象
			Class.forName(driver);
			conn = DriverManager.getConnection(url+dbname,uid,pwd);
		} catch (ClassNotFoundException e) {
				e.printStackTrace();
		} catch (SQLException e) {
				e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
//	声明静态方法，关闭数据库连接
	public static void closeConnection(){
		if(conn!=null){
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
	public static void main(String[] args) {
		ConnectionFactory.getConnection();
	}
}
